const Web3 = require('web3');
const web3 = new Web3('http://127.0.0.1:7545');
import { flABI } from './flABI';
// 合约配置
const CONTRACT_ADDRESS = '0xee6F38580f93311C4f35123CeaC35Cf28Acd90dA';
const PRIVATE_KEY = '0xb487848dd5de2adfca060a5cc75b2e847b6472f540c20dcf64b92d2870d1df04';
const ABI = flABI; // 合约ABI

// 创建合约实例
const contract = new web3.eth.Contract(ABI, CONTRACT_ADDRESS);

// 账户处理
const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
web3.eth.defaultAccount = account.address;

// 获取记录
export const getRecord = async (taskId) => {
  try {
    const result = await contract.methods.getRecord(taskId).call();
    const blockNumber = await web3.eth.getBlockNumber();
    const blockInfo = await web3.eth.getBlock(blockNumber);

    return {
      success: true,
      data: {
        datasetName: result[0],
        taskId: result[1],
        batchSize: result[2],
        aggregationCount: result[3],
        lastTrainAccuracy: result[4],
        lastTestAccuracy: result[5],
        averageTrainingTime: result[6],
        trainingStartTime: result[7],
        blockNumber: blockNumber, // 返回当前区块高度
        hash: blockInfo.hash,
        timestamp: blockInfo.timestamp,
        transactionCount: blockInfo.transactions.length
      }
    };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

// 上传记录
export const uploadRecord = async (
  datasetName,
  taskId,
  batchSize,
  aggregationCount,
  lastTrainAccuracy,
  lastTestAccuracy,
  averageTrainingTime,
  trainingStartTime
) => {
  try {
    const nonce = await web3.eth.getTransactionCount(account.address);
    const gasPrice = await web3.eth.getGasPrice();

    const txData = contract.methods.uploadRecord(
      datasetName,
      taskId,
      batchSize,
      aggregationCount,
      lastTrainAccuracy,
      lastTestAccuracy,
      averageTrainingTime,
      trainingStartTime
    ).encodeABI();

    const tx = {
      from: account.address,
      to: CONTRACT_ADDRESS,
      gas: 2000000,
      gasPrice,
      nonce,
      data: txData
    };

    const signedTx = await account.signTransaction(tx);
    const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
    
    return {
      success: true,
      txHash: receipt.transactionHash,
      blockNumber: receipt.blockNumber
    };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

// 获取区块和合约信息
export const getBlockAndContractInfo = async (blockNumber) => {
  try {
    const blockInfo = await web3.eth.getBlock(blockNumber);
    
    return {
      success: true,
        block: {
          hash: blockInfo.hash,
          timestamp: blockInfo.timestamp,
          transactionCount: blockInfo.transactions.length
        },
    };
  } catch (error) {
    return { success: false, error: error.message };
  }
};
export const getLatestBlockInfo = async () => {
    try {
      const latestBlock = await web3.eth.getBlock('latest'); // 获取最新区块信息

      // 检查是否成功获取最新区块信息
      if (!latestBlock) {
        throw new Error('Failed to retrieve the latest block.');
      }
  
      return {
        success: true,
        data: {
          blockNumber: latestBlock.number, // 最新区块高度
          hash: latestBlock.hash, // 最新区块哈希
          timestamp: latestBlock.timestamp, // 最新区块时间戳
          transactionCount: latestBlock.transactions.length, // 最新区块中的交易数量
          miner: latestBlock.miner, // 矿工地址
          difficulty: latestBlock.difficulty, // 区块难度
          size: latestBlock.size // 区块大小（字节）
        }
      };
    } catch (error) {
      return { success: false, error: error.message }; // 错误处理
    }
  };
  